package com.leetcode.partition1;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/7/28 11:07
 */
public class LC53最大子序和 {

    public static int maxSubArray(int[] nums) {
        return dynamicProgramming(nums);
    }

    public static void main(String[] args) {
        int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray(arr));
    }

    private static int greedy(int[] nums) {
        int answer = Integer.MIN_VALUE;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            answer = Math.max(answer, sum); //取区间累积的最大值，相当于不断确定最大子序列的终止位置
            if (sum < 0) sum = 0;           //重置最大子序列的起始位置
        }
        return answer;
    }

    public static int dynamicProgramming(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int result = dp[0];
        for (int i = 1; i < dp.length; i++) {
            //对于nums[i]，只有两种情况，要么取，要么不取
            dp[i] = Math.max(nums[i], nums[i] + dp[i - 1]);
            result = Math.max(result, dp[i]);
        }
        System.out.println(Arrays.toString(dp));
        return result;
    }

    public static int divide(int[] nums) {
        return getMax(nums, 0, nums.length - 1);
    }

    public static int getMax(int[] nums, int left, int right) {
        // 数组被分为一个为一组时，最大的就是本身
        if (left == right)
            return nums[left];
        int mid = (left + right) / 2;
        int leftMax = getMax(nums, left, mid);
        int rightMax = getMax(nums, mid + 1, right);
        int crossMax = getCrossMax(nums, left, right);
        return Math.max(Math.max(leftMax, rightMax), crossMax);
    }

    public static int getCrossMax(int[] nums, int left, int right) {
        int mid = (left + right) / 2;
        int leftSum = nums[mid];
        int leftMax = leftSum;
        // 查找左边
        for (int i = mid - 1; i >= 0; i--) {
            leftSum += nums[i];
            leftMax = Math.max(leftMax, leftSum);
        }
        int rightSum = nums[mid + 1];
        int rightMax = rightSum;
        // 查找右边
        for (int i = mid + 2; i < nums.length; i++) {
            rightSum += nums[i];
            rightMax = Math.max(rightMax, rightSum);
        }
        return leftMax + rightMax;
    }

    public static int violence(int[] nums) {
        int result = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                result = Math.max(result, sum);
            }
        }
        return result;
    }
}
